package com.sunxd.zstudy.juc;

import lombok.Data;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 线程信息独享，别人拿不到
 * // ****使用完了要手动remove掉，要不然出现内存泄漏
 * 用途：spring声明事务
 * @author: 作者名称
 * @date: 2021-09-07 16:11
 **/
public class T17_ThreadLocal {

    public static void main(String[] args) {
        ThreadLocal<Person> threadLocal = new ThreadLocal<>();



        new Thread( () -> {
            Person p1 = new Person();
            p1.setName("zhangsan");
            threadLocal.set(p1);
            Person p2 = new Person();
            p2.setName("lisi");
            threadLocal.set(p2);
            System.out.println(threadLocal.get().name);
            // ****使用完了要手动remove掉，要不然出现内存泄漏
            threadLocal.remove();
        },"t1").start();
        new Thread( () -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(Objects.nonNull(threadLocal.get())){
                System.out.println(threadLocal.get().name);
            }else {
                System.out.println("null");
            }
            threadLocal.remove();
        },"t2").start();


    }



    @Data
    static
    class Person{
        private String name;
    }

}
